package cn.cjy.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cjy.model.Article;
import cn.cjy.service.ArticleService;
import cn.cjy.service.impl.ArticleServiceImpl;

/**
 * Servlet implementation class AdminAddArticleServlet
 */
@WebServlet("/AdminAddArticleServlet")
public class AdminAddArticleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AdminAddArticleServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		// response.setCharacterEncoding("utf-8");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String catalogs = request.getParameter("catalogs");
		String cover = request.getParameter("cover");
		String userinfo = request.getParameter("userinfo");
		String posttime = request.getParameter("posttime");
		String review = request.getParameter("review");

		Article article = new Article();
		article.setTitle(title);
		article.setContent(content);
		article.setCatalogs(catalogs);
		article.setCover(cover);
		article.setUserinfo(userinfo);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format.parse(posttime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		article.setPosttime(date);
		article.setReview(review);

		ArticleService articleService = new ArticleServiceImpl();
		int n = articleService.add(article);
		if (n >= 1) {
			request.setAttribute("information", "发布成功");
			request.setAttribute("url", "SelectAllArticleServlet");
			request.setAttribute("second", 3);
			RequestDispatcher dispatcher = request.getRequestDispatcher("admin/tip.jsp");
			dispatcher.forward(request, response);
		} else {
			request.setAttribute("information", "发布失败");
			request.setAttribute("url", "SelectAllArticleServlet");
			request.setAttribute("second", 3);
			RequestDispatcher dispatcher = request.getRequestDispatcher("admin/tip.jsp");
			dispatcher.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
